package com.three.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String path = request.getRequestURI();
        //判断资源是否放行
        if ("/login.jsp".equals(path) ||
            "/staff/login".equals(path) ||
            "/login/sendValidateCode".equals(path) ||
            "/login/identityVerification".equals(path) ||
            path.endsWith(".css")||
            path.endsWith(".js")||
            path.endsWith(".png")||
            path.endsWith(".jpeg")||
            path.endsWith(".jpg")||
            path.endsWith(".gif")||
            path.endsWith(".ico")||
            path.endsWith(".webp")
        ) {
            filterChain.doFilter(request, response);
        } else {
            //判断是否登录
            Object staff = request.getSession().getAttribute("staff");
            if (staff == null) {
                //未登录，跳转登录页面
                response.sendRedirect("/login.jsp");
            } else {
                //已登录，放行
                filterChain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
